package com.bizmda.bizsip.converter;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bizmda.bizsip.common.*;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;


/**
 * @author 史正烨
 */
public class VelocityJsonConverter extends AbstractConverter {
    private final VelocityEngine velocityEngine = new VelocityEngine();
    @Override
    public void init(String configPath,Map<String,Object> messageMap) throws BizException {
        super.init(configPath,messageMap);
        if (configPath == null) {
            velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
            velocityEngine.setProperty("class.resource.loader.class" , ClasspathResourceLoader.class.getName());
        }
        else {
            velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, this.configPath + "/converter");
        }
        velocityEngine.setProperty(RuntimeConstants.ENCODING_DEFAULT, BizConstant.DEFAULT_CHARSET_NAME);
        velocityEngine.setProperty(RuntimeConstants.OUTPUT_ENCODING, BizConstant.DEFAULT_CHARSET_NAME);
        velocityEngine.init();
    }

    @Override
    protected JSONObject biz2json(JSONObject inMessage) {
        return inMessage;
    }

    @Override
    protected byte[] json2adaptor(JSONObject inMessage) throws BizException {
        Map<String,Object> map = new HashMap<>(16);
        map.put("data",inMessage);
        VelocityContext velocityContext = new VelocityContext(map);
        StringWriter stringWriter = new StringWriter();
        String templateFileName = this.matchMessagePredicateRule(this.packRules,inMessage);
        if (templateFileName == null) {
            throw new BizException(BizResultEnum.CONVERTOR_NOTFOUND_MATCH_RULE);
        }
        if (this.configPath == null) {
            templateFileName = "/converter/" + templateFileName;
        }
        Template template = this.velocityEngine.getTemplate(templateFileName,"UTF-8");
        template.merge(velocityContext, stringWriter);
        return BizTools.getBytes(stringWriter.toString());
    }

    @Override
    protected JSONObject adaptor2json(byte[] inBytes) throws BizException {
        return JSONUtil.parseObj(BizTools.getString(inBytes));
    }

    @Override
    protected JSONObject json2biz(JSONObject inMessage) {
        return inMessage;
    }
}
